﻿Public Class frmSampleRequestEntry
    Dim dbSystem As New dbSystem
    Dim dbSales As New dbSales
    Dim Var As New varDeclare
    Dim frmCtrl As New FormControl
    Dim dsBase As DataSet
    Dim dsItem As DataSet
    Public EntryID As String
    Dim dgvTemp As New DataGridView
    Dim ca As String
    Dim TypeAct As String

    Private Sub GenerateDataGridView()
        Dim colTextBox As New DataGridViewTextBoxColumn
        Dim colButton As New DataGridViewButtonColumn
        Dim colComboBox As New DataGridViewComboBoxColumn
        Dim colImage As New DataGridViewImageColumn
        Dim colCheckBox As New DataGridViewCheckBoxColumn
        Dim colLink As New DataGridViewLinkColumn
        Dim colCalendar As New DataGridViewDatePickerColumn()
        dgvBase.Columns.Add(colCalendar)
        With dgvBase
            .Columns(4).Name = "clDeliveryDate"
            .Columns(4).HeaderText = "DELIVERY DATE"
            .Columns(4).Width = 145
            .Columns(4).Resizable = DataGridViewTriState.False
            .Columns(4).AutoSizeMode = DataGridViewAutoSizeColumnMode.None
            .Columns(4).SortMode = DataGridViewColumnSortMode.NotSortable
        End With
    End Sub

    Private Sub frmSampleRequestEntry_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.WindowState = FormWindowState.Maximized
        txtSampleNumber.Text = EntryID
        dgvTemp.Columns.Add("clID", "clID")
        dgvTemp.Rows.Add(EntryID)
        ToolbarHeader1.DefaultRow = 1
        ToolbarHeader1.Iniliaze("Entry : Quotation", Me, New frmSampleRequestList, dgvTemp, "clID")
        GenerateDataGridView()
        If (EntryID = "") Then
            ToolbarHeader1.ActionCtrl(False, False, False, False, False, False, False, False, True)
            txtSampleNumber.Text = dbSales.LastNumberSampleRequest(dtDocDate.Value.ToString("yyyy"))
            TypeAct = "I"
            refreshLine()
        Else
            TypeAct = "U"
            ToolbarHeader1.ActionCtrl(True, False, True, True, True, False, False, True, True)
            gbHeader.Enabled = False
            dgvBase.ReadOnly = True
            dgvBase.ContextMenuStrip = Nothing
            dsBase = dbSales.GetSampleRequestDetail(EntryID)
            If (dsBase IsNot Nothing) Then
                ca = "LOAD"
                Try
                    Dim dtHeader As DataTable = dsBase.Tables(0)
                    Dim dtLine As DataTable = dsBase.Tables(1)
                    If (dtHeader.Rows(0)("Status").ToString() = "1") Then
                        ToolbarHeader1.ActionCtrl(True, False, False, False, True, False, False, True, True)
                    Else
                        ToolbarHeader1.tsApprove.Visible = True
                    End If
                    dtDocDate.Value = CDate(dtHeader.Rows(0)("DocDate").ToString())
                    lblQuotationCode.Text = dtHeader.Rows(0)("QuotationCode").ToString()
                    txtCustCode.Text = dtHeader.Rows(0)("CustCode").ToString()
                    txtCustCompany.Text = dtHeader.Rows(0)("CustCompany").ToString()
                    cmbAttSolut.Text = dtHeader.Rows(0)("ContactSal").ToString()
                    txtAttentionname.Text = dtHeader.Rows(0)("ContactName").ToString()
                    txtAddress.Text = dtHeader.Rows(0)("DelAddr").ToString()
                    txtCity.Text = dtHeader.Rows(0)("DelCity").ToString()
                    txtZip.Text = dtHeader.Rows(0)("DelZip").ToString()
                    txtCountry.Text = dtHeader.Rows(0)("DelCoun").ToString()
                    txtPhone.Text = dtHeader.Rows(0)("DelPhon").ToString()
                    txtFax.Text = dtHeader.Rows(0)("DelFax").ToString()
                    txtNotes.Text = dtHeader.Rows(0)("DelNote").ToString()
                    txtRef.Text = dtHeader.Rows(0)("Reff").ToString()
                    Dim dr As DataRow
                    For Each dr In dtLine.Rows
                        dgvBase.Rows.Add(dr("ItemCode").ToString(), dr("ItemDesc").ToString(), dr("ItemUOM").ToString(), dr("ItemQty").ToString(), CDate(dr("ItemDelDate")))
                    Next
                Catch ex As Exception
                    MessageBox.Show("Error in Load Data")
                End Try
                dgvBase.Rows.Add(1)
                ca = "FINISH"
            End If
        End If
    End Sub

    Private Function validateForm() As Boolean
        Dim val As Boolean = True
        If (txtSampleNumber.Text.Trim() = "" Or txtCustCompany.Text.Trim() = "" Or txtRef.Text.Trim() = "" Or txtAddress.Text.Trim() = "" Or dgvBase.ReadOnly) Then
            val = False
        End If
        Return val
    End Function

    ''================================== Control Header ==============================================''
    Private Sub tsNew_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsNewClick
        Dim OpenForm As New frmSampleRequestEntry
        OpenForm.EntryID = ""
        frmCtrl.OpenFormDetail(Me, OpenForm)
    End Sub

    Private Sub tsEdit_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsEditClick
        ToolbarHeader1.ActionCtrl(False, False, False, False, False, True, True, False, True)
        dgvBase.ReadOnly = False
        gbHeader.Enabled = True
        dtDocDate.Enabled = False
        dgvBase.ContextMenuStrip = cmsGL
        TypeAct = "U"
        refreshLine()
    End Sub

    Private Sub tsDelete_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsDeleteClick
        If (EntryID.Trim() <> "") Then
            'Dim result As Boolean = dbGL.deleteJournalGL(txtQuotationNumber.Text, Var.CompID)
            frmCtrl.openChild(New frmSampleRequestList, Me.ParentForm)
        Else : MessageBox.Show("Please Choose Quotation")
        End If
    End Sub

    Private Sub tsSave_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsSaveClick
        If (validateForm()) Then
            Dim x As Array = txtSampleNumber.Text.Split(" / ")
            EntryID = dbSales.SaveSampleRequest(x(0).ToString(), _
                                                 dtDocDate.Value, _
                                                 txtCustCode.Text.Trim(), _
                                                 lblQuotationCode.Text.Trim(), _
                                                 txtRef.Text.Trim(), _
                                                 txtAddress.Text.Trim(), _
                                                 txtCity.Text.Trim(), _
                                                 txtZip.Text.Trim(), _
                                                 txtCountry.Text.Trim(), _
                                                 txtPhone.Text.Trim(), _
                                                 txtFax.Text.Trim(), _
                                                 txtNotes.Text.Trim(), _
                                                 cmbAttSolut.Text.Trim(), _
                                                 txtAttentionname.Text.Trim(), _
                                                 MDI.LoginID, _
                                                 TypeAct)
            Dim Seq As Integer
            Dim status As Boolean = True
            For i = 0 To dgvBase.Rows.Count - 2
                If (status) Then
                    If (dgvBase.Rows(i).Cells("clChoose").Value.ToString() <> "") Then
                        Seq = i + 1
                        Dim GroupCode As Array = dgvBase.Rows(i).Cells("clChoose").Value.ToString().Split("-")
                        status = dbSales.SaveSampleRequestLine(EntryID, _
                                                        dtDocDate.Value, _
                                                        txtCustCode.Text.Trim(), _
                                                        GroupCode(0), _
                                                        GroupCode(1), _
                                                        dgvBase.Rows(i).Cells("clDesc").Value.ToString(), _
                                                        dgvBase.Rows(i).Cells("clUOM").Value.ToString(), _
                                                        dgvBase.Rows(i).Cells("clQty").Value.ToString(), _
                                                        dgvBase.Rows(i).Cells("clDeliveryDate").Value.ToString())

                    End If
                End If
            Next
            If (status) Then
                frmCtrl.openChild(frmSampleRequestList, Me.ParentForm)
            Else
                MessageBox.Show("Saving Quotation " + EntryID + " , Failed at Seq" + Seq.ToString())
            End If
        End If
    End Sub

    Private Sub tsPrint_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsPrintClick
        'Dim journalCode As Array = EntryID.Split("-")
        'Dim JournalNo As Array = journalCode(1).ToString().Split("/")
        'Dim dsReport As DataSet = New dbReport().GenerateJournalReport(journalCode(0).ToString().Trim(), JournalNo(1).ToString().Trim(), "", JournalNo(0).ToString().Trim(), JournalNo(0).ToString().Trim())
        'If (dsReport IsNot Nothing) Then
        '    Dim frmViewReport As New ViewReport
        '    frmViewReport.strReport = "Journal"
        '    frmViewReport.dsReport = dsReport
        '    frmViewReport.Show()
        'End If
    End Sub

    Private Sub tsRefresh_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsRefreshClick
        Dim OpenForm As New frmSampleRequestEntry
        OpenForm.EntryID = EntryID
        frmCtrl.OpenFormDetail(Me, OpenForm)
    End Sub

    Private Sub tsCancel_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsCancelClick
        Dim OpenForm As New frmSampleRequestEntry
        OpenForm.EntryID = EntryID
        frmCtrl.OpenFormDetail(Me, OpenForm)
    End Sub

    Private Sub tsApprove_Click(ByVal sender As ToolbarHeader) Handles ToolbarHeader1.tsApproveClick
        If (EntryID.Trim() <> "") Then
            Dim answer As DialogResult
            answer = MessageBox.Show("Are you sure Posting data. " & EntryID & " ?", "Posting Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If answer = vbYes Then
                If (dbSales.PostingSampleRequest(EntryID)) Then
                    frmCtrl.openChild(New frmSampleRequestList, Me.ParentForm)
                Else : MessageBox.Show("Failed to Posting Sample Request")
                End If
            End If
        Else : MessageBox.Show("Please Choose Sample Request")
        End If
    End Sub
    ''================================== Control Header [End] ==============================================''
    <System.Diagnostics.DebuggerStepThrough()> _
    Function IsHeaderButtonCell(ByVal GridView As DataGridView, ByVal e As DataGridViewCellEventArgs) As Boolean
        Return TypeOf GridView.Columns(e.ColumnIndex) Is DataGridViewButtonColumn AndAlso Not e.RowIndex = -1
    End Function

    Private Sub dgvBase_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvBase.CellClick
        If (validateForm()) Then
            If (IsHeaderButtonCell(dgvBase, e)) Then
                Dim formFind As New frmFind
                formFind.lblTitle.Text = "Search : Item Code"
                formFind.QueryHeader = "SELECT GROUPS + '-' + CODE 'ID',IC_DESCRIPTION 'Name' From SALES_PRICE WITH(NOLOCK)"
                formFind.StartPosition = FormStartPosition.CenterScreen
                formFind.type = "cell"
                formFind.dgCellValue1 = dgvBase.Rows(e.RowIndex).Cells("clChoose")
                formFind.dgCellValue2 = dgvBase.Rows(e.RowIndex).Cells("clDesc")
                formFind.Show()
                MDI.Enabled = False
            End If
        End If
    End Sub

    Private Sub dgvBase_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles dgvBase.CellValueChanged
        If (dgvBase.Rows.Count > 0) Then
            If (e.RowIndex > -1) Then
                Select Case e.ColumnIndex
                    Case 0
                        Dim dvItem As DataView = New DataView(dsItem.Tables(0))
                        dvItem.RowFilter = "[GROUPS] + '-' + [CODE] = '" & dgvBase.Rows(e.RowIndex).Cells("clChoose").Value & "'"
                        dgvBase.Rows(e.RowIndex).Cells("clUOM").Value = dvItem.Item(0).Row("UOM").ToString()
                        dgvBase.Rows(e.RowIndex).Cells("clQty").Value = "1"
                End Select
            End If
            refreshLine()
        End If
    End Sub

    Private Sub refreshLine()
        Dim subTotal As Decimal = 0
        Dim ct As Integer = 0
        For i = 0 To dgvBase.Rows.Count - 2
            Try
                If (dgvBase.Rows(i).Cells("clQty").Value = "" Or IsNumeric(dgvBase.Rows(i).Cells("clQty").Value) = False) Then
                    dgvBase.Rows(i).Cells("clQty").Value = "1"
                End If
                If (Convert.ToDecimal(dgvBase.Rows(i).Cells("clQty").Value) < 1) Then
                    MessageBox.Show("Amount can't minus")
                    dgvBase.Rows(i).Cells("clQty").Value = "1"
                End If
                If (dgvBase.Rows(i).Cells("clChoose").Value.ToString() <> "") Then
                    ct += 1
                End If
            Catch ex As Exception

            End Try
        Next
        If (ct = dgvBase.Rows.Count) Then
            dgvBase.Rows.Add(1)
            If (dgvBase.ReadOnly = False) Then
                ToolbarHeader1.ActionCtrl(False, False, False, False, False, True, True, False, True)
                dgvBase.ContextMenuStrip = cmsGL
            End If
        End If
    End Sub

    Private Sub btnQuotationCode_Click(sender As Object, e As EventArgs) Handles btnQuotationCode.Click
        Dim formFind As New frmFind
        formFind.lblTitle.Text = "Search : GL Journal Group"
        formFind.QueryHeader = "SELECT Number [QuotationCode], CustomerPO, DateCustomerPO, Customer FROM v_QuotationList WHERE SampleRequestCode IS NULL AND CustomerPO IS NOT NULL AND COMP = " + Var.CompID
        formFind.StartPosition = FormStartPosition.CenterScreen
        formFind.type = "lbl"
        formFind.lblValue = lblQuotationCode
        formFind.Show()
        MDI.Enabled = False
    End Sub

    Private Sub lblQuotationCode_TextChanged(sender As Object, e As EventArgs) Handles lblQuotationCode.TextChanged
        If (ca <> "LOAD") Then
            Dim dtQuotation As DataTable = dbSystem.FreeQueryDataTable("SELECT * FROM v_QuotationList WHERE Number = '" & lblQuotationCode.Text & "' AND COMP = '" & Var.CompID & "'")
            If (dtQuotation.Rows.Count > 0) Then
                txtCustCode.Text = dtQuotation.Rows(0)("Cust Code").ToString().Trim()
                txtAttentionname.Text = dtQuotation.Rows(0)("Client").ToString().Trim()
                txtOffice.Text = dtQuotation.Rows(0)("OFFICE").ToString().Trim()
                cmbAttSolut.Text = dtQuotation.Rows(0)("SALUTATION").ToString().Trim()
                txtPhone.Text = dtQuotation.Rows(0)("PHONE").ToString().Trim()
                txtFax.Text = dtQuotation.Rows(0)("FAX").ToString().Trim()
                txtRef.Text = dtQuotation.Rows(0)("CustomerPO").ToString().Trim()
                Dim dsLine As DataSet = dbSales.GetQuotationLine(lblQuotationCode.Text)
                If (dsLine.Tables(0).Rows.Count() > 0) Then
                    dgvBase.Rows.Add(dsBase.Tables(0).Rows.Count)
                    For i = 0 To dsBase.Tables(0).Rows.Count - 1
                        Try
                            dgvBase.Rows(i).Cells("clChoose").Value = dsLine.Tables(0).Rows(i)("ITEM").ToString().Trim()
                            dgvBase.Rows(i).Cells("clDesc").Value = dsLine.Tables(0).Rows(i)("IC_DESCRIPTION").ToString().Trim()
                            dgvBase.Rows(i).Cells("clUOM").Value = dsLine.Tables(0).Rows(i)("PRO_UOM").ToString().Trim()
                        Catch ex As Exception
                        End Try
                    Next
                End If
            End If
        End If
    End Sub

    Private Sub btnSearchAttention_Click(sender As Object, e As EventArgs) Handles btnSearchAttention.Click
        If (txtCustCompany.Text <> "") Then
            Dim formFind As New frmFind
            formFind.lblTitle.Text = "Search : GL Journal Group"
            formFind.QueryHeader = "SELECT (CUST_OFF_MNG + '-' + CAST(CCID_SEQ_NUMBER AS VARCHAR) [SEQ], SALUTATION [Salutation], CCID_CONTACT_NAME [Full Name], CCID_POSITION [Position], CCID_EMAIL [Email] FROM CUSTOMER_CONTACT WHERE CUSTOMER_CODE = '" & txtCustCode.Text & "' AND CCID_CONTACT_NAME IS NOT NULL"
            formFind.StartPosition = FormStartPosition.CenterScreen
            formFind.type = "txt"
            formFind.txtValue = txtSeq
            formFind.Show()
            MDI.Enabled = False
        End If
    End Sub

    Private Sub txtSeq_TextChanged(sender As Object, e As EventArgs) Handles txtSeq.TextChanged
        If (ca <> "LOAD") Then
            If (txtSeq.Text.Trim().Length > 0) Then
                Dim seq As Array = txtSeq.Text.Split("-")
                Dim dtContact As DataTable = New dbSystem().FreeQueryDataTable("SELECT TOP 1 SALUTATION, CCID_CONTACT_NAME FROM CUSTOMER_CONTACT WHERE CUSTOMER_CODE = '" & txtCustCode.Text & "' AND CUST_OFF_MNG = '" & seq(0) & "' AND CCID_SEQ_NUMBER = '" & seq(1) & "' AND CCID_CONTACT_NAME IS NOT NULL")
                If (dtContact.Rows.Count > 0) Then
                    cmbAttSolut.Text = dtContact.Rows(0)("SALUTATION").ToString().Trim()
                    txtAttentionname.Text = dtContact.Rows(0)("CCID_CONTACT_NAME").ToString().Trim()
                Else
                    cmbAttSolut.Text = ""
                    txtAttentionname.Text = ""
                End If
            Else
                txtAttentionname.Text = ""
                cmbAttSolut.Text = ""
            End If
        End If
    End Sub

    Private Sub btnAddress_Click(sender As Object, e As EventArgs) Handles btnAddress.Click
        If (txtCustCompany.Text <> "") Then
            Dim formFind As New frmFind
            formFind.lblTitle.Text = "Search : GL Journal Group"
            formFind.QueryHeader = "SELECT Office, Addr, Phone, Fax FROM vCustomer WHERE code = " + txtCustCode.Text
            formFind.StartPosition = FormStartPosition.CenterScreen
            formFind.type = "txt"
            formFind.txtValue = txtOffice
            formFind.Show()
            MDI.Enabled = False
        End If
    End Sub

    Private Sub txtOffice_TextChanged(sender As Object, e As EventArgs) Handles txtOffice.TextChanged
        If (ca <> "LOAD") Then
            If (txtOffice.Text.Trim().Length > 0) Then
                Dim dtPhone As DataTable = New dbSystem().FreeQueryDataTable("SELECT Addr, City, Zip, Country, Phone, Fax FROM vCustomer WHERE code = '" & txtCustCode.Text & "' AND office = '" & txtOffice.Text & "'")
                If (dtPhone.Rows.Count > 0) Then
                    txtAddress.Text = dtPhone.Rows(0)("Addr").ToString().Trim()
                    txtCity.Text = dtPhone.Rows(0)("City").ToString().Trim()
                    txtZip.Text = dtPhone.Rows(0)("Zip").ToString().Trim()
                    txtCountry.Text = dtPhone.Rows(0)("Country").ToString().Trim()
                    txtPhone.Text = dtPhone.Rows(0)("Phone").ToString().Trim()
                    txtFax.Text = dtPhone.Rows(0)("Fax").ToString().Trim()
                Else
                    txtAddress.Text = ""
                    txtCity.Text = ""
                    txtZip.Text = ""
                    txtCountry.Text = ""
                    txtPhone.Text = ""
                    txtFax.Text = ""
                End If
            Else
                txtAddress.Text = ""
                txtCity.Text = ""
                txtZip.Text = ""
                txtCountry.Text = ""
                txtPhone.Text = ""
                txtFax.Text = ""
            End If
        End If
    End Sub

    Private Sub dtDocDate_ValueChanged(sender As Object, e As EventArgs) Handles dtDocDate.ValueChanged
        If (TypeAct <> "U") Then txtSampleNumber.Text = dbSales.LastNumberSampleRequest(dtDocDate.Value.ToString("yyyy"))
    End Sub
End Class